package com.example.graduatetest.utils;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.example.graduatetest.bean.User;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

public class Constant {
    //https://www.blueskyhome.work:8080
    public static String www = "http://kwg9yy.natappfree.cc";
//    public static String www = "http://175.27.224.196:8080";
    private static String grade;
    private static User user;
    //url 图像识别相关
    public static String ADDURL = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add";
    public static String SEARCHURL = "https://aip.baidubce.com/rest/2.0/face/v3/search";
    //appkey
    public static String clientId = "1AoUl5uFhLt7ZLv2ETPYFpB7";
    // 官网获取的 Secret Key 更新为你注册的
    public  static String clientSecret = "fXWmMB4yL5LBp4kGcePNtnKGELNjUy6E";

    public static String setGradeFun(int number,String format){

        if(format.equals("百分制")){
            if(number < 60){
                grade = "不及格";
            }else if(number < 70){
                grade = "及格";
            }else if(number < 80){
                grade = "良好";
            }else if(number < 90){
                grade = "优秀";
            }else{
                grade = "满绩点";
            }
        }else{
            if(number < 90){
                grade = "不及格";
            }else if(number < 100){
                grade = "及格";
            }else if(number < 120){
                grade = "良好";
            }else if(number < 140){
                grade = "优秀";
            }else{
                grade = "满绩点";
            }
        }
        return grade;
    }

    public static User checkStudentOrTeacher(Activity activity){
        user = new User();
        SharedPreferences preferences = activity.getSharedPreferences("data", Context.MODE_PRIVATE);
        user.setLogin(preferences.getBoolean("isLogin", false));
        user.setName(preferences.getString("name", "默认"));
        user.setPassword(preferences.getString("password", "123456"));
        user.setStudent(preferences.getBoolean("isStudent", true));
        user.setNumber(preferences.getString("number", "2017211973"));
        return user;
    }

    //获取百度人脸识别token
    public static String getAuth(String ak, String sk) {
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.err.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }

            System.err.println("result:" + result);
            JSONObject jsonObject = new JSONObject(result);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (Exception e) {
            Log.e("haha","获取token失败！");
            e.printStackTrace(System.err);
        }
        return null;
    }

    //获取Bitmap对象
    public static Bitmap getImage(String srcPath) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;

        //此时返回bm为空
//        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        Bitmap bitmap;

        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;

        //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = 800f;//这里设置高度为800f
        float ww = 480f;//这里设置宽度为480f

        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (w > h && w > ww) {
            //如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {
            //如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0) {
            be = 1;
        }

        //设置缩放比例
        newOpts.inSampleSize = be;

        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        Bitmap bitmap1 = Constant.compressImage(bitmap);
        //压缩好比例大小后再进行质量压缩
        return bitmap1;
    }

    //质量压缩
    public static Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream by = new ByteArrayOutputStream();

        //质量压缩方法，这里100表示不压缩，把压缩后的数据存放到by中
        image.compress(Bitmap.CompressFormat.JPEG, 100, by);
        int options = 100;
        while (by.toByteArray().length / 1024 > 300) {
            //循环判断如果压缩后图片是否大于300kb,大于继续压缩
            by.reset();

            //重置by即清空by
            image.compress(Bitmap.CompressFormat.JPEG, options, by);//这里压缩options%，把压缩后的数据存放到baos中

            //每次都减少10
            options -= 10;
        }

        //把压缩后的数据baos存放到ByteArrayInputStream中
        ByteArrayInputStream isBm = new ByteArrayInputStream(by.toByteArray());

        //把ByteArrayInputStream数据生成图片
        return BitmapFactory.decodeStream(isBm, null, null);
    }

    //bitmap对象转化为byte[]数组
    public static byte[] getBytesByBitmap(Bitmap bitmap) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(bitmap.getByteCount());
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
        return outputStream.toByteArray();
    }
}
